

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="dayu">
  <meta name="keywords" content="">
  
    <meta name="description" content="KOA21.KOA2 的介绍 基于 Node.js 平台的 Web 服务器框架  由 Express 原班人马打造，Express Koa , Koa2 都是 Web 服务器的框架  环境依赖 Node v7.6.0 及以上  由于 Koa2 它是支持 async 和 await ，所以它对 Node 的版本是有要求的，它要求 Node 的版本至 少是在 7.6 级以上,因为语法糖 async 和">
<meta property="og:type" content="article">
<meta property="og:title" content="数据可视化项目一">
<meta property="og:url" content="http://example.com/2022/11/14/%E6%95%B0%E6%8D%AE%E5%8F%AF%E8%A7%86%E5%8C%96%E9%A1%B9%E7%9B%AE%E4%B8%80/index.html">
<meta property="og:site_name" content="Dayu">
<meta property="og:description" content="KOA21.KOA2 的介绍 基于 Node.js 平台的 Web 服务器框架  由 Express 原班人马打造，Express Koa , Koa2 都是 Web 服务器的框架  环境依赖 Node v7.6.0 及以上  由于 Koa2 它是支持 async 和 await ，所以它对 Node 的版本是有要求的，它要求 Node 的版本至 少是在 7.6 级以上,因为语法糖 async 和">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-11-13T17:14:17.000Z">
<meta property="article:modified_time" content="2023-09-05T13:21:06.468Z">
<meta property="article:author" content="dayu">
<meta property="article:tag" content="koa">
<meta name="twitter:card" content="summary_large_image">
  
  
  
  <title>数据可视化项目一 - Dayu</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>dayu</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="数据可视化项目一"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-11-14 01:14" pubdate>
          2022年11月14日 凌晨
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          5.1k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          43 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">数据可视化项目一</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="KOA2"><a href="#KOA2" class="headerlink" title="KOA2"></a>KOA2</h1><h2 id="1-KOA2-的介绍"><a href="#1-KOA2-的介绍" class="headerlink" title="1.KOA2 的介绍"></a>1.KOA2 的介绍</h2><ul>
<li><p>基于 Node.js 平台的 Web 服务器框架</p>
</li>
<li><p>由 Express 原班人马打造，Express Koa , Koa2 都是 Web 服务器的框架</p>
</li>
<li><p>环境依赖 Node v7.6.0 及以上</p>
</li>
<li><p>由于 Koa2 它是支持 async 和 await ，所以它对 Node 的版本是有要求的，它要求 Node 的版本至 少是在 7.6 级以上,因为语法糖 async 和 await 是在 Node7.6 版本之后出现才支持</p>
</li>
<li><p>洋葱模型的中间件</p>
<ul>
<li>当一个请求到达咱们的服务器，最先最先处理这个请求的是第一层中间件</li>
<li>第一层的中间件在处理这个请求之后，它会把这个请求给第二层的中间件</li>
<li>第二层的中间件在处理这个请求之后，它会把这个请求给第三层的中间件</li>
<li>第三层中间件内部并没有中间件了, 所以第三层中间件在处理完所有的代码之后，这个请求又 会到了第二层的中间件，所以第二层中间件对这个请求经过了两次的处处理</li>
<li>第二层的中间件在处理完这个请求之后，又到了第一层的中间件, 所以第一层的中间件也对这 个请求经过了两次的处理</li>
</ul>
<p>这个调用顺序就是洋葱模型, 中间件对请求的处理有一种先进后出的感觉，请求最先到达第一层中 间件，而最后也是第一层中间件对请求再次处理了一下</p>
</li>
</ul>
<h2 id="2-KOA-的快速上手"><a href="#2-KOA-的快速上手" class="headerlink" title="2.KOA 的快速上手"></a>2.KOA 的快速上手</h2><p>如何对 Koa2 进行快速的上手呢?需要有如下几个步骤</p>
<ul>
<li><p>检查 Node 的版本 <code>node-v</code></p>
</li>
<li><p>安装 Koa2</p>
<ul>
<li><code>npm init -y</code></li>
<li><code>npm i koa</code></li>
</ul>
</li>
<li><p>编写入口文件 app.js</p>
<ul>
<li><p>创建 Koa 的实例对象</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 1.创建koa对象</span><br><span class="hljs-keyword">const</span> <span class="hljs-title class_">Koa</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;koa&#x27;</span>) <span class="hljs-comment">// 导入构造方法</span><br><span class="hljs-keyword">const</span> app = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Koa</span>() <span class="hljs-comment">// 通过构造方法, 创建实例对象</span><br></code></pre></td></tr></table></figure></li>
<li><p>编写响应函数(中间件)</p>
<p>响应函数是通过 use 的方式才能产生效果, 这个函数有两个参数, 一个是 ctx ,一个是 next</p>
<ul>
<li>ctx: 上下文, 指的是请求所处于的 Web 容器,我们可以通过 ctx.request 拿到请求对象, 也可 以通过 ctx.response 拿到响应对象</li>
<li>next: 内层中间件执行的入口</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 2.编写响应函数(中间件)</span><br>app.<span class="hljs-title function_">use</span>(<span class="hljs-function">(<span class="hljs-params">ctx, next</span>) =&gt;</span> &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(ctx.<span class="hljs-property">request</span>.<span class="hljs-property">url</span>)<br>  ctx.<span class="hljs-property">response</span>.<span class="hljs-property">body</span> = <span class="hljs-string">&#x27;hello world&#x27;</span><br>&#125;)<br></code></pre></td></tr></table></figure></li>
<li><p>指明端口号</p>
<p>通过 app.listen 就可以指明一个端口号</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 3.绑定端口号 3000</span><br>app.<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>)<br></code></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p>启动服务器</p>
<p>通过 node app.js 就可以启动服务器了</p>
<p>随即打开浏览器, 在浏览器中输入 127.0.0.1:3000/ 你将会看到浏览器中出现 hello world 的字符 串, 并且在服务器的终端中, 也能看到请求的 url</p>
</li>
</ul>
<h2 id="3-KOA2-中间件的特点"><a href="#3-KOA2-中间件的特点" class="headerlink" title="3.KOA2 中间件的特点"></a>3.KOA2 中间件的特点</h2><ul>
<li><p>Koa2 的实例对象通过 use 方法加入一个中间件</p>
</li>
<li><p>一个中间件就是一个函数,这个函数具备两个参数,分别是 ctx 和 next</p>
</li>
<li><p>中间件的执行符合洋葱模型</p>
</li>
<li><p>内层中间件能否执行取决于外层中间件的 next 函数是否调用</p>
</li>
<li><p>调用 next 函数得到的是 Promise 对象, 如果想得到 Promise 所包装的数据, 可以结合 await 和 async</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js">app.<span class="hljs-title function_">use</span>(<span class="hljs-keyword">async</span> (ctx, next) =&gt; &#123;<br>  <span class="hljs-comment">// 刚进入中间件想做的事情</span><br>  <span class="hljs-keyword">await</span> <span class="hljs-title function_">next</span>()<br>  <span class="hljs-comment">// 内层所有中间件结束之后想做的事情</span><br>&#125;)<br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="4-后台项目的开发"><a href="#4-后台项目的开发" class="headerlink" title="4.后台项目的开发"></a>4.后台项目的开发</h2><h3 id="4-1-后台项目的目标"><a href="#4-1-后台项目的目标" class="headerlink" title="4.1 后台项目的目标"></a>4.1 后台项目的目标</h3><ul>
<li><p>计算服务器处理请求的总耗时</p>
<p>计算出服务器对于这个请求它的所有中间件总耗时时长究竟是，我们需要计算一下</p>
</li>
<li><p>在响应头上加上响应内容的 mime 类型</p>
<p>加入 mime 类型, 可以让浏览器更好的来处理由服务器返回的数据. 如果响应给前端浏览器是 json 格式的数据，这时候就需要在咱们的响应头当中增加 Content-Type 它的值就是 application/json ， application/json 就是 json 数据类型的 mime 类型</p>
</li>
<li><p>根据 URL 读取指定目录下的文件内容</p>
<p>为了简化后台服务器的代码，前端图表所要的数据, 并没有存在数据库当中，而是将存在文件当中 的，这种操作只是为了简化咱们后台的代码. 所以咱们是需要去读取某一个目录下面的文件内容 的。</p>
</li>
</ul>
<p>每一个目标就是一个中间件需要实现的功能, 所以后台项目中需要有三个中间件</p>
<h3 id="4-2-后台项目的开发步骤"><a href="#4-2-后台项目的开发步骤" class="headerlink" title="4.2.后台项目的开发步骤"></a>4.2.后台项目的开发步骤</h3><p>创建一个新的文件夹, 叫做 koa_server , 这个文件夹就是后台项目的文件夹</p>
<ul>
<li>项目准备<ul>
<li>安装包<ul>
<li><code>npm init -y</code></li>
<li><code>npm install koa</code></li>
</ul>
</li>
<li>创建文件和目录结构<ul>
<li>app.js 是后台服务器的入口文件</li>
<li>data 目录是用来存放所有模块的 json 文件数据</li>
<li>middleware 是用来存放所有的中间件代码</li>
<li>koa_response_data.js 是业务逻辑中间件</li>
<li>koa_response_duration.js 是计算服务器处理时长的中间件</li>
<li>koa_response_header.js 是用来专门设置响应头的中间件</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>接着将各个模块的 json 数据文件复制到 data 的目录之下, 接着在 app.js 文件中写上代码如下:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 服务器的入口文件</span><br><span class="hljs-comment">// 1.创建KOA的实例对象</span><br><span class="hljs-keyword">const</span> <span class="hljs-title class_">Koa</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;koa&#x27;</span>)<br><span class="hljs-keyword">const</span> app = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Koa</span>()<br><span class="hljs-comment">// 2.绑定中间件</span><br><span class="hljs-comment">// 绑定第一层中间件</span><br><span class="hljs-comment">// 绑定第二层中间件</span><br><span class="hljs-comment">// 绑定第三层中间件</span><br><span class="hljs-comment">// 3.绑定端口号 8888</span><br>app.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8888</span>)<br></code></pre></td></tr></table></figure>

<ul>
<li><p>总耗时中间件</p>
<ul>
<li><p>第 1 层中间件</p>
<p>总耗时中间件的功能就是计算出服务器所有中间件的总耗时，应该位于第一层，因为第一层 的中间件是最先处理请求的中间件，同时也是最后处理请求的中间件</p>
</li>
<li><p>计算执行时间</p>
<p>第一次进入咱们中间件的时候，就记录一个开始的时间 当其他所有中间件都执行完之后，再记录下结束时间以后 将两者相减就得出总耗时</p>
</li>
<li><p>设置响应头</p>
<p>将计算出来的结果,设置到响应头的 X-Response-Time 中, 单位是毫秒 ms</p>
</li>
</ul>
</li>
</ul>
<p>具体代码如下:</p>
<p><code>app.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 绑定第一层中间件</span><br><span class="hljs-keyword">const</span> respDurationMiddleware = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;./middleware/koa_response_duration&#x27;</span>)<br>app.<span class="hljs-title function_">use</span>(respDurationMiddleware)<br></code></pre></td></tr></table></figure>

<p><code>koa_response_duration.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 计算服务器消耗时长的中间件</span><br><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">async</span> (ctx, next) =&gt; &#123;<br><span class="hljs-comment">// 记录开始时间</span><br><span class="hljs-keyword">const</span> start = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>()<br><span class="hljs-comment">// 让内层中间件得到执行</span><br><span class="hljs-keyword">await</span> <span class="hljs-title function_">next</span>()<br><span class="hljs-comment">// 记录结束的时间</span><br><span class="hljs-keyword">const</span> end = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>()<br><span class="hljs-comment">// 设置响应头 X-Response-Time</span><br><span class="hljs-keyword">const</span> duration = end - start<br><span class="hljs-comment">// ctx.set 设置响应头</span><br>ctx.<span class="hljs-title function_">set</span>(<span class="hljs-string">&#x27;X-Response-Time&#x27;</span>, duration + <span class="hljs-string">&#x27;ms&#x27;</span>)<br></code></pre></td></tr></table></figure>

<ul>
<li><p>响应头中间件</p>
<ul>
<li><p>第 2 层中间件</p>
<p>这个第 2 层中间件没有特定的要求</p>
</li>
<li><p>获取 mime 类型</p>
<p>由于咱们所响应给前端浏览器当中的数据都是 json 格式的字符串，所以 mime 类型可以统一 的给它写成 application/json , 当然这一块也是简化的处理了，因为 mime 类型有几十几百 种，我们我们没有必要在我们的项目当中考虑那么多，所以这里简化处理一下</p>
</li>
<li><p>设置响应头</p>
<p>响应头的 key 是 Content-Type ，它的值是 application/json , 顺便加上 charset=utf-8 告诉浏览器，我这部分响应的数据，它的类型是 application/json ，同时它的编码是 utf-8</p>
</li>
</ul>
</li>
</ul>
<p>具体代码如下:</p>
<p><code>app.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 绑定第二层中间件</span><br><span class="hljs-keyword">const</span> respHeaderMiddleware = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;./middleware/koa_response_header&#x27;</span>)<br>app.<span class="hljs-title function_">use</span>(respHeaderMiddleware)<br></code></pre></td></tr></table></figure>

<p><code>koa_response_header.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 设置响应头的中间件</span><br><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">async</span> (ctx, next) =&gt; &#123;<br>  <span class="hljs-keyword">const</span> contentType = <span class="hljs-string">&#x27;application/json; charset=utf-8&#x27;</span><br>  ctx.<span class="hljs-title function_">set</span>(<span class="hljs-string">&#x27;Content-Type&#x27;</span>, contentType)<br>  <span class="hljs-keyword">await</span> <span class="hljs-title function_">next</span>()<br>&#125;<br></code></pre></td></tr></table></figure>

<ul>
<li><p>业务逻辑中间件</p>
<ul>
<li><p>.第 3 层中间件</p>
<p>这个第 3 层中间件没有特定的要求</p>
</li>
<li><p>读取文件内容</p>
<ul>
<li><p>获取 URL 请求路径</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> url = ctx.<span class="hljs-property">request</span>.<span class="hljs-property">url</span><br></code></pre></td></tr></table></figure></li>
<li><p>根据 URL 请求路径,拼接出文件的绝对路径</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> filePath = url.<span class="hljs-title function_">replace</span>(<span class="hljs-string">&#x27;/api&#x27;</span>, <span class="hljs-string">&#x27;&#x27;</span>)<br>filePath = <span class="hljs-string">&#x27;../data&#x27;</span> + filePath + <span class="hljs-string">&#x27;.json&#x27;</span><br>filePath = path.<span class="hljs-title function_">join</span>(__dirname, filePath)<br></code></pre></td></tr></table></figure>

<p>这个 filePath 就是需要读取文件的绝对路径</p>
</li>
<li><p>读取这个文件的内容</p>
<p>使用 fs 模块中的 readFile 方法进行实现</p>
</li>
</ul>
</li>
<li><p>设置响应体</p>
<p><code>ctx.response.body</code></p>
</li>
</ul>
</li>
</ul>
<p>具体代码如下:</p>
<p><code>app.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 绑定第三层中间件</span><br><span class="hljs-keyword">const</span> respDataMiddleware = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;./middleware/koa_response_data&#x27;</span>)<br>app.<span class="hljs-title function_">use</span>(respDataMiddleware)<br></code></pre></td></tr></table></figure>

<p><code>koa_response_data.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 处理业务逻辑的中间件,读取某个json文件的数据</span><br><span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;path&#x27;</span>)<br><span class="hljs-keyword">const</span> fileUtils = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;../utils/file_utils&#x27;</span>)<br><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">async</span> (ctx, next) =&gt; &#123;<br>  <span class="hljs-comment">// 根据url</span><br>  <span class="hljs-keyword">const</span> url = ctx.<span class="hljs-property">request</span>.<span class="hljs-property">url</span> <span class="hljs-comment">// /api/seller ../data/seller.json</span><br>  <span class="hljs-keyword">let</span> filePath = url.<span class="hljs-title function_">replace</span>(<span class="hljs-string">&#x27;/api&#x27;</span>, <span class="hljs-string">&#x27;&#x27;</span>) <span class="hljs-comment">// /seller</span><br>  filePath = <span class="hljs-string">&#x27;../data&#x27;</span> + filePath + <span class="hljs-string">&#x27;.json&#x27;</span> <span class="hljs-comment">// ../data/seller.json</span><br>  filePath = path.<span class="hljs-title function_">join</span>(__dirname, filePath)<br>  <span class="hljs-keyword">try</span> &#123;<br>    <span class="hljs-keyword">const</span> ret = <span class="hljs-keyword">await</span> fileUtils.<span class="hljs-title function_">getFileJsonData</span>(filePath)<br>    ctx.<span class="hljs-property">response</span>.<span class="hljs-property">body</span> = ret<br>  &#125; <span class="hljs-keyword">catch</span> (error) &#123;<br>    <span class="hljs-keyword">const</span> errorMsg = &#123;<br>      <span class="hljs-attr">message</span>: <span class="hljs-string">&#x27;读取文件内容失败, 文件资源不存在&#x27;</span>,<br>      <span class="hljs-attr">status</span>: <span class="hljs-number">404</span>,<br>    &#125;<br>    ctx.<span class="hljs-property">response</span>.<span class="hljs-property">body</span> = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(errorMsg)<br>  &#125;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(filePath)<br>  <span class="hljs-keyword">await</span> <span class="hljs-title function_">next</span>()<br>&#125;<br></code></pre></td></tr></table></figure>

<p><code>file_utils.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 读取文件的工具方法</span><br><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;fs&#x27;</span>)<br><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>.<span class="hljs-property">getFileJsonData</span> = <span class="hljs-function">(<span class="hljs-params">filePath</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">// 根据文件的路径, 读取文件的内容</span><br>  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> &#123;<br>    fs.<span class="hljs-title function_">readFile</span>(filePath, <span class="hljs-string">&#x27;utf-8&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">error, data</span>) =&gt;</span> &#123;<br>      <span class="hljs-keyword">if</span> (error) &#123;<br>        <span class="hljs-comment">// 读取文件失败</span><br>        <span class="hljs-title function_">reject</span>(error)<br>      &#125; <span class="hljs-keyword">else</span> &#123;<br>        <span class="hljs-comment">// 读取文件成功</span><br>        <span class="hljs-title function_">resolve</span>(data)<br>      &#125;<br>    &#125;)<br>  &#125;)<br>&#125;<br></code></pre></td></tr></table></figure>

<ul>
<li><p>允许跨域</p>
<ul>
<li><p>设置响应头</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js">app.<span class="hljs-title function_">use</span>(<span class="hljs-keyword">async</span> (ctx, next) =&gt; &#123;<br>	ctx.<span class="hljs-title function_">set</span>(<span class="hljs-string">&quot;Access-Control-Allow-Origin&quot;</span>, <span class="hljs-string">&quot;*&quot;</span>)<br>	ctx.<span class="hljs-title function_">set</span>(<span class="hljs-string">&quot;Access-Control-Allow-Methods&quot;</span>, <span class="hljs-string">&quot;OPTIONS, GET, PUT, POST,</span><br><span class="hljs-string">DELETE&quot;</span>)<br>	<span class="hljs-keyword">await</span> <span class="hljs-title function_">next</span>();<br>&#125;)<br></code></pre></td></tr></table></figure></li>
</ul>
</li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E6%95%B0%E6%8D%AE%E5%8F%AF%E8%A7%86%E5%8C%96%E9%A1%B9%E7%9B%AE/" class="category-chain-item">数据可视化项目</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/koa/">#koa</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>数据可视化项目一</div>
      <div>http://example.com/2022/11/14/数据可视化项目一/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>dayu</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年11月14日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/11/16/%E6%95%B0%E6%8D%AE%E5%8F%AF%E8%A7%86%E5%8C%96%E9%A1%B9%E7%9B%AE%E4%BA%8C/" title="数据可视化项目二">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">数据可视化项目二</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/11/14/JSX/" title="JSX">
                        <span class="hidden-mobile">JSX</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
